package com.easylinkin.linkappapi.security.config.admin;

import com.easylinkin.security.config.RestLogoutSuccessHandler;
import com.easylinkin.security.config.SmUsernamePasswordAuthenticationFilter;
import com.easylinkin.security.service.SmLoginService;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.filter.CharacterEncodingFilter;


/**
 * 安全认证配置
 *
 * @author TianGanLin
 * @since 1.0.0, 2019/8/28
 */
@Configuration
@EnableWebSecurity
@Order(2)
public class SmSecurityConfiguration extends WebSecurityConfigurerAdapter {
	
	@Resource
	SmLoginService smLoginService ;
	/**
	 * 注册用户认证服务
	 */
	@Override
	public SmLoginService userDetailsService() {
		return smLoginService;
	}
	
	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		AuthenticationManager manager = super.authenticationManagerBean();
		return manager;
	}
	
	@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(smLoginService);
    }


	@Bean
	AdminUserPhoneLoginAuthenticationFilter adminUserPhoneLoginAuthenticationFilter() throws Exception {
		AdminUserPhoneLoginAuthenticationFilter filter = new AdminUserPhoneLoginAuthenticationFilter();
		filter.setAuthenticationManager(super.authenticationManagerBean());
		filter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler);
		filter.setAuthenticationFailureHandler(restAuthenticationFailureHandler);
		return filter;
	}

	@Bean
	SmUsernamePasswordAuthenticationFilter myAuthenticationFilter() throws Exception {
		SmUsernamePasswordAuthenticationFilter filter = new SmUsernamePasswordAuthenticationFilter();
		filter.setAuthenticationManager(authenticationManagerBean());
		filter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler);
		filter.setAuthenticationFailureHandler(restAuthenticationFailureHandler);
		return filter;
	}
	

	@Autowired
	private RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;

	@Autowired
	private RestAuthenticationFailureHandler restAuthenticationFailureHandler;

	@Autowired
	private RestLogoutSuccessHandler restLogoutSuccessHandler;

	@Override
	protected void configure(HttpSecurity http) throws Exception {

		//		解决 spring security 对于开放接口返回乱码的解决
		CharacterEncodingFilter filter = new CharacterEncodingFilter();
		filter.setEncoding("UTF-8");
		filter.setForceEncoding(true);
		http.addFilterBefore(filter, CsrfFilter.class);

		http
				// 禁止匿名用户
				// .anonymous().disable()
				// 禁止csrf
				.csrf().disable()
				// 认证失败处理
				.exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
				.and()
				// 白名单
				.authorizeRequests()
				.antMatchers("/swagger-ui.html", "/webjars/**", "/swagger-resources/**", "/v2/api-docs/**",
						"/user/verificationCode", "/user/sendVerificationCode", "/user/verificationMessages","/user/resetPassword",
						"/linkappUser/verificationCode","/adminUser/verificationCode","/adminUser/isEnableVerificationCode", "/linkappUser/sendVerificationCode", "/linkappUser/verificationMessages","/linkappUser/resetPassword",
						"/program/getProgramInfo/*", "/lang", "/checkhealth","/datapush",
						"/synchronizationLinkthing","/ssoLogin","/tenant/getSSOUrl","/tenant/addLinkappTenant","/adminlogin","/application/getPersonalIfo",
						"/personality/getPersonalIfo","/onlineStateChange", "/anon/**", "/miniappLogin","/linkappUser/verificationCode/**","/phoneLogin","/adminPhoneLogin", "/meterLogin", "/meterCodeLogin", "/recharge/thirdAsynNotify", "/resident/verificationCode", "/resident/checkVerificationCode", "/resident/updatePwdByForget",
						"/selectAllPrivilegeByApplication","/selectPrivilegeByApplication","/selectPersonalityByApplication","/initLinkappTenant","/updatePrivilegePersonalityByApplication",
						"/getTenantInfo","/updateTenantAccount")
				.permitAll()
				// 接口调试阶段 目前不校验接口 modify by tongjie
				.anyRequest().authenticated().and()
				// 表单登录配置
				.formLogin()
				// 登录成功处理
				.successHandler(restAuthenticationSuccessHandler)
				// 登录失败处理
				.failureHandler(restAuthenticationFailureHandler).and()
				// 登出成功处理
				.logout().logoutSuccessHandler(restLogoutSuccessHandler);

	}
}
